﻿using DoNet.Common.Helpers;
using DoNet.Token;
using DoNet.Token.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DoNet.TokenWeb.Controllers
{
    [ApiController]
    //[Route("api/[controller]")]
    [Route("api/app")]
    public class AppController : ControllerBase //ApiController
    {
        private string connectionString = string.Empty;
        public AppController(IConfiguration config)
        {
            connectionString = config.GetConnectionString("DbDefault");
        }

        [HttpGet("get")]
        public ApiResult Index()
        {
            StringGenerate stringGenerate = new StringGenerate();
            string appId = "cs" + stringGenerate.Create(16).ToLower();
            string secret = "";
            var model = AppService.GetAppByAppId(appId);
            if (model != null)
            {
                secret = model.AppSecret;
            }
            else
            {
                secret = StringHelper.GenerateSecureToken();
                secret = stringGenerate.Create(32).ToLower();
                AppService.StoreApp(appId, secret);
            }

            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (SqlCommand sqlCommand = new SqlCommand())
                {
                    sqlCommand.Connection = sqlConnection;
                    sqlCommand.CommandText = "SELECT * FROM dbo.Product";
                    sqlCommand.CommandType = CommandType.Text;
                    //sqlCommand.Parameters.Clear();

                    using (SqlDataReader reader = sqlCommand.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {

                            }
                        }
                    }
                }
            }


            return ApiResultHelper.Success(new { AppId = appId, AppSecret = secret });
        }
    }
}
